package com.xmut.mall.store.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xmut.mall.store.constant.StoreStatusConstant;
import com.xmut.mall.store.dao.StoreDetailDao;
import com.xmut.mall.store.dto.*;
import com.xmut.mall.store.entity.StoreDetailEntity;
import com.xmut.mall.store.entity.StoreInfoEntity;
import com.xmut.mall.store.feign.MemberFeignService;
import com.xmut.mall.store.myexpection.UpdateDataException;
import com.xmut.mall.store.service.StoreDetailService;
import com.xmut.mall.store.service.StoreInfoService;
import com.xmut.mall.store.utils.RespBean;
import com.xmut.mall.store.vo.MemberReceiveAddressVo;
import com.xmut.mall.store.vo.StoreDetailVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service("storeDetailService")
public class StoreDetailServiceImpl extends ServiceImpl<StoreDetailDao, StoreDetailEntity> implements StoreDetailService {

    @Autowired
    private StoreInfoService storeInfoService;

    @Autowired
    private MemberFeignService memberFeignService;

    /**
     * 申请店铺第一步-填写企业信息
     *
     * @return
     */
    @Transactional
    @Override
    public RespBean applyFirst(StoreCompanyDTO dto) {
        // 前置判断当前用户是否已经填写了店铺信息
        StoreInfoEntity store = storeInfoService.getOne(new QueryWrapper<StoreInfoEntity>()
                .eq("member_id", dto.getMemberId()));

        if (store == null) {
            // 该用户尚未填写店铺信息
            // 生成店铺信息
            StoreInfoEntity storeInfo = new StoreInfoEntity();
            storeInfo.setMemberId(dto.getMemberId());
            storeInfo.setMemberName(dto.getMemberName());
            storeInfo.setCreateTime(new Date());
            storeInfoService.save(storeInfo);

            // 拷贝storeDetail 插入表
            StoreDetailEntity storeDetail = new StoreDetailEntity();
            BeanUtils.copyProperties(dto, storeDetail);
            storeDetail.setStoreId(IdWorker.getId());
            storeDetail.setStoreId(storeInfo.getId());
            RespBean receiveAddress = memberFeignService.getDefaultReceiveAddressById(dto.getMemberId());
            if (receiveAddress.getCode() == 201) {
                // 请求成功
                MemberReceiveAddressVo addressVo = JSON.parseObject(JSON.toJSONString(receiveAddress.getObj()), MemberReceiveAddressVo.class);
                // 设置店铺收货和发货信息
                storeDetail.setSalesConsigneeAddressPath(addressVo.getConsigneeAddressPath());
                storeDetail.setSalesConsignorAddressPath(addressVo.getConsigneeAddressPath());
                storeDetail.setSalesConsignorDetail(addressVo.getDetail());
                storeDetail.setSalesConsigneeDetail(addressVo.getDetail());
                storeDetail.setSalesConsignorMobile(addressVo.getMobile());
                storeDetail.setSalesConsigneeMobile(addressVo.getMobile());
                storeDetail.setSalesConsigneeName(addressVo.getName());
                storeDetail.setSalesConsignorName(addressVo.getName());
            }

            this.save(storeDetail);
            return RespBean.success("保存企业信息成功");
        } else {
            // 如果当前用户以及填写了店铺信息 直接属性对拷
            BeanUtils.copyProperties(dto, store);
            storeInfoService.updateById(store);

            // 判断是否存在店铺详情
            StoreDetailEntity detail = this.getOne(new QueryWrapper<StoreDetailEntity>()
                    .eq("store_id", store.getId()));
            if (detail == null) {
                // 如果不存在detail 直接属性对拷dto
                StoreDetailEntity storeDetail = new StoreDetailEntity();
                BeanUtils.copyProperties(dto, storeDetail);
                this.save(storeDetail);
                return RespBean.success("保存企业信心成功");
            } else {
                // 如果存在detail
                BeanUtils.copyProperties(dto, detail);
                this.updateById(detail);
                return RespBean.success("保存企业信息成功");
            }
        }
    }

    /**
     * 申请店铺第二步-填写银行信息
     *
     * @param dto
     * @return
     */
    @Override
    public RespBean applySecond(StoreBankDto dto) {
        StoreInfoEntity store = storeInfoService.getOne(new QueryWrapper<StoreInfoEntity>()
                .eq("member_id", dto.getMemberId()));
        if (store == null) {
            return RespBean.error("店铺不存在");
        } else {
            StoreDetailEntity storeDetail = this.getOne(new QueryWrapper<StoreDetailEntity>()
                    .eq("store_id", store.getId()));
            // 属性对拷
            BeanUtils.copyProperties(dto, storeDetail);
            boolean result = this.updateById(storeDetail);
            if (result) {
                return RespBean.success("填写成功");
            } else {
                return RespBean.error("填写失败");
            }
        }
    }

    /**
     * 申请店铺第三步-完善其他信息
     *
     * @param dto
     * @return
     */
    @Override
    public RespBean applyThird(StoreOtherInfoDTO dto) {
        StoreInfoEntity store = storeInfoService.getOne(new QueryWrapper<StoreInfoEntity>()
                .eq("member_id", dto.getMemberId()));
        if (store == null) {
            return RespBean.error("店铺不存在");
        } else {
            StoreDetailEntity storeDetail = this.getOne(new QueryWrapper<StoreDetailEntity>()
                    .eq("store_id", store.getId()));
            // 属性对拷
            BeanUtils.copyProperties(dto, storeDetail);
            storeDetail.setGoodsManagementCategory(dto.getGoodsManagementCategory());
            storeDetail.setStockWarning(10l);
            boolean detailResult = this.updateById(storeDetail);

            store.setStoreName(dto.getStoreName());
            store.setStoreLogo(dto.getStoreLogo());
            store.setStoreManagementCategory(dto.getGoodsManagementCategory());
            store.setStoreStatus(StoreStatusConstant.STORE_APPLYING);
            store.setStoreCenter(dto.getStoreCenter());
            store.setStoreAddressIdPath(dto.getStoreAddressIdPath());
            store.setStoreAddressDetail(dto.getStoreAddressDetail());
            store.setStoreAddressPath(dto.getStoreAddressPath());
            store.setStoreDesc(dto.getStoreDesc());
            // 生成店铺的各种评分 默认满分
            store.setDeliveryScore(5.00);
            store.setDescriptionScore(5.00);
            store.setServiceScore(5.00);
            boolean infoResult = storeInfoService.updateById(store);
            if (detailResult == true && infoResult == true) {
                return RespBean.success("申请成功，请等待平台方审核");
            } else {
                return RespBean.error("申请失败，请重试");
            }
        }
    }

    /**
     * 更id获取商品详细信息
     *
     * @param id
     * @return
     */
    @Override
    public RespBean getStoreDetail(Long id) {
        StoreInfoEntity storeInfo = storeInfoService.getById(id);
        StoreDetailEntity storeDetail = this.getOne(new QueryWrapper<StoreDetailEntity>().eq("store_id", id));

        if (storeInfo != null) {
            StoreDetailVo storeDetailVo = new StoreDetailVo();
            // 属性对拷
            BeanUtils.copyProperties(storeInfo, storeDetailVo);
            BeanUtils.copyProperties(storeDetail, storeDetailVo);
            storeDetailVo.setId(id);

            RespBean receiveAddress = memberFeignService.getDefaultReceiveAddressById(storeInfo.getMemberId());
            if (receiveAddress.getCode() == 201) {
                // 请求成功
                MemberReceiveAddressVo addressVo = JSON.parseObject(JSON.toJSONString(receiveAddress.getObj()), MemberReceiveAddressVo.class);
                // 设置店铺收货人信息
                storeDetailVo.setSalesConsigneeName(addressVo.getName());
                storeDetailVo.setSalesConsigneeMobile(addressVo.getMobile());
                storeDetailVo.setSalesConsigneeAddressPath(addressVo.getConsigneeAddressPath());
                storeDetailVo.setSalesConsigneeDetail(addressVo.getDetail());
                storeDetailVo.setSalesConsigneeAddressId(addressVo.getConsigneeAddressIdPath());
            }

            return RespBean.success("获取成功", storeDetailVo);
        } else {
            return RespBean.error("店铺不存在");
        }
    }

    /**
     * 编辑商铺信息
     *
     * @param id
     * @param dto
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public RespBean editShop(Long id, StoreEditDTO dto) {
        StoreInfoEntity storeInfo = new StoreInfoEntity();
        // 属性对拷
        BeanUtils.copyProperties(dto, storeInfo);
        storeInfo.setId(id);
        StringBuffer categoryBuffer = new StringBuffer();
        for (String s : dto.getGoodsManagementCategory()) {
            categoryBuffer.append(s + ",");
        }
        storeInfo.setStoreManagementCategory(categoryBuffer.toString());
        boolean infoResult = storeInfoService.updateById(storeInfo);
        System.out.println("测试info" + storeInfo);


        StoreDetailEntity storeDetail = new StoreDetailEntity();
        // 属性对拷
        BeanUtils.copyProperties(dto, storeDetail);
        // 法人照片
        StringBuffer legalPhotoBuffer = new StringBuffer();
        for (String s : dto.getLegalPhoto()) {
            legalPhotoBuffer.append(s + ",");
        }

        // 设置结算周期
        StringBuffer cycleBuffer = new StringBuffer();
        for (String s : dto.getSettlementCycle()) {
            cycleBuffer.append(s + ",");
        }
        storeDetail.setSettlementCycle(cycleBuffer.toString());
        System.out.println("测试Detail:"+storeDetail);
        boolean detailResult = this.update(storeDetail, new QueryWrapper<StoreDetailEntity>().eq("store_id", id));

        if(infoResult && detailResult){
            // 如果两个都更新成功才成功
            return RespBean.success("修改成功");
        }else {
            try {
                throw new UpdateDataException();
            } catch (UpdateDataException e) {
                e.printStackTrace();
            }
            return RespBean.error("修改失败");
        }

    }

    /**
     * 管理端审核商铺信息 进行通过 或 驳回
     * @param shopId
     * @param status
     * @return
     */
    @Override
    public RespBean auditShop(Long shopId, String status) {
        StoreInfoEntity shop = storeInfoService.getById(shopId);
        if(shop==null){
            return RespBean.error("该商铺不存在");
        }
        if(status.equals("PASS")){
            // 店铺审核通过
            boolean update = storeInfoService.update(new UpdateWrapper<StoreInfoEntity>()
                    .eq("id", shopId)
                    .set("store_status", "OPEN"));
            if(update){
                return RespBean.success("操作成功");
            }else{
                return RespBean.error("网络异常请稍后重试");
            }
        }else if(status.equals("REFUSED")){
            // 拒绝店铺审核通过
            boolean update = storeInfoService.update(new UpdateWrapper<StoreInfoEntity>()
                    .eq("id", shopId)
                    .set("store_status", status));
            if(update){
                return RespBean.success("操作成功");
            }else {
                return RespBean.error("网络异常请稍后重试");
            }
        }else {
            // 如果传进来的状态码是其他东西
            return RespBean.error("状态码错误");
        }
    }

    /**
     * 获取商家售后收件地址
     * @param storeId
     * @return
     */
    @Override
    public RespBean getStoreAfterSaleAddress(Long storeId) {
        StoreAfterSaleAddressDTO storeAfterSaleAddressDTO = this.baseMapper.getStoreAfterSaleAddressDTO(storeId);

        return RespBean.success("获取成功",storeAfterSaleAddressDTO);
    }
}
